/// 选择器组件
/// 参照Element UI的Select控件实现

import 'package:flutter/material.dart';
import 'e_input.dart';
import '../../core/elegance_theme.dart';
import '../../core/elegance_base.dart';

/// 选择器选项组件
class EOption<T> extends StatelessWidget {
  /// 创建选项组件
  const EOption({
    super.key,
    required this.value,
    required this.label,
    this.disabled = false,
    this.isSelected = false,
    this.onSelect,
  });

  /// 选项的值
  final T value;

  /// 选项的标签文本
  final String label;

  /// 是否禁用
  final bool disabled;

  /// 是否被选中
  final bool isSelected;

  /// 选中时的回调
  final Function(T)? onSelect;

  @override
  Widget build(BuildContext context) {
    final theme = EleganceTheme.of(context);
    final color = disabled 
        ? theme.textPlaceholderColor
        : isSelected 
            ? theme.primaryColor
            : theme.textPrimaryColor;

    return GestureDetector(
      onTap: disabled ? null : () => onSelect?.call(value),
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
        color: isSelected ? theme.primaryLight.withOpacity(0.2) : Colors.transparent,
        child: Text(
          label,
          style: TextStyle(
            color: color,
            fontSize: 14,
          ),
        ),
      ),
    );
  }
}

/// 选择器选项分组组件
class EOptionGroup<T> extends StatelessWidget {
  /// 创建选项分组组件
  const EOptionGroup({
    super.key,
    required this.label,
    required this.children,
    this.disabled = false,
  });

  /// 分组的标签文本
  final String label;

  /// 分组内的选项
  final List<Widget> children;

  /// 是否禁用整个分组
  final bool disabled;

  @override
  Widget build(BuildContext context) {
    final theme = EleganceTheme.of(context);
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
          child: Text(
            label,
            style: TextStyle(
              color: theme.textSecondaryColor,
              fontSize: 12,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
        Column(children: children),
      ],
    );
  }
}

/// 选择器组件
class ESelect<T> extends StatefulWidget {
  /// 创建选择器组件
  const ESelect({
    super.key,
    this.value,
    this.multiple = false,
    this.disabled = false,
    this.valueKey = 'value',
    this.size = EInputSize.normal,
    this.clearable = false,
    this.collapseTags = false,
    this.multipleLimit = 0,
    this.name,
    this.placeholder = '请选择',
    this.filterable = false,
    this.allowCreate = false,
    this.filterMethod,
    this.remote = false,
    this.remoteMethod,
    this.loading = false,
    this.loadingText = '加载中',
    this.noMatchText = '无匹配数据',
    this.noDataText = '无数据',
    this.popperClass,
    this.reserveKeyword = false,
    this.defaultFirstOption = false,
    this.popperAppendToBody = true,
    this.automaticDropdown = false,
    this.onChange,
    this.onVisibleChange,
    this.onRemoveTag,
    this.onClear,
    this.onBlur,
    this.onFocus,
    this.empty,
    this.prefix,
    required this.children,
  });

  /// 绑定值
  final dynamic value;

  /// 是否多选
  final bool multiple;

  /// 是否禁用
  final bool disabled;

  /// 作为value唯一标识的键名
  final String valueKey;

  /// 输入框尺寸
  final EInputSize size;

  /// 是否可以清空选项
  final bool clearable;

  /// 多选时是否将选中值按文字的形式展示
  final bool collapseTags;

  /// 多选时用户最多可以选择的项目数，为0则不限制
  final int multipleLimit;

  /// select input的name属性
  final String? name;

  /// 占位符
  final String placeholder;

  /// 是否可搜索
  final bool filterable;

  /// 是否允许用户创建新条目，需配合filterable使用
  final bool allowCreate;

  /// 自定义搜索方法
  final bool Function(String, Widget)? filterMethod;

  /// 是否为远程搜索
  final bool remote;

  /// 远程搜索方法
  final void Function(String)? remoteMethod;

  /// 是否正在从远程获取数据
  final bool loading;

  /// 远程加载时显示的文字
  final String loadingText;

  /// 搜索条件无匹配时显示的文字
  final String noMatchText;

  /// 选项为空时显示的文字
  final String noDataText;

  /// Select下拉框的类名
  final String? popperClass;

  /// 多选且可搜索时，是否在选中一个选项后保留当前的搜索关键词
  final bool reserveKeyword;

  /// 在输入框按下回车，选择第一个匹配项
  final bool defaultFirstOption;

  /// 是否将弹出框插入至body元素
  final bool popperAppendToBody;

  /// 对于不可搜索的Select，是否在输入框获得焦点后自动弹出选项菜单
  final bool automaticDropdown;

  /// 选中值发生变化时触发
  final ValueChanged<dynamic>? onChange;

  /// 下拉框出现/隐藏时触发
  final ValueChanged<bool>? onVisibleChange;

  /// 多选模式下移除tag时触发
  final ValueChanged<dynamic>? onRemoveTag;

  /// 可清空的单选模式下用户点击清空按钮时触发
  final VoidCallback? onClear;

  /// 当input失去焦点时触发
  final ValueChanged<FocusNode>? onBlur;

  /// 当input获得焦点时触发
  final ValueChanged<FocusNode>? onFocus;

  /// 无选项时的自定义内容
  final Widget? empty;

  /// 自定义前缀内容
  final Widget? prefix;

  /// 选项列表
  final List<Widget> children;

  @override
  State<ESelect<T>> createState() => _ESelectState<T>();
}

class _ESelectState<T> extends State<ESelect<T>> with ThemedMixin {
  /// 焦点节点
  final FocusNode _focusNode = FocusNode();

  /// 搜索文本控制器
  final TextEditingController _searchController = TextEditingController();

  /// 是否显示下拉菜单
  bool _showDropdown = false;

  /// 是否聚焦
  bool _isFocused = false;

  /// 过滤后的选项
  List<Widget> _filteredOptions = [];

  /// 本地选项缓存（用于搜索）
  List<_OptionData<T>> _optionsCache = [];

  @override
  void initState() {
    super.initState();
    _initOptionsCache();
    _filteredOptions = List.from(widget.children);

    // 监听焦点变化
    _focusNode.addListener(() {
      setState(() {
        _isFocused = _focusNode.hasFocus;
      });

      if (_isFocused && widget.automaticDropdown && !widget.filterable) {
        _toggleDropdown();
      }

      if (widget.onFocus != null && _isFocused) {
        widget.onFocus!(_focusNode);
      }

      if (widget.onBlur != null && !_isFocused) {
        widget.onBlur!(_focusNode);
      }
    });

    // 监听搜索文本变化
    _searchController.addListener(() {
      if (widget.filterable) {
        _filterOptions(_searchController.text);
      }

      if (widget.remote && widget.remoteMethod != null) {
        widget.remoteMethod!(_searchController.text);
      }
    });
  }

  @override
  void didUpdateWidget(covariant ESelect<T> oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.children != widget.children) {
      _initOptionsCache();
      _filteredOptions = List.from(widget.children);
    }
  }

  @override
  void dispose() {
    _focusNode.dispose();
    _searchController.dispose();
    super.dispose();
  }

  /// 初始化选项缓存
  void _initOptionsCache() {
    _optionsCache.clear();
    _collectOptions(widget.children);
  }

  /// 收集选项数据
  void _collectOptions(List<Widget> children) {
    for (var child in children) {
      if (child is EOption<T>) {
        _optionsCache.add(
          _OptionData<T>(
            value: child.value,
            label: child.label,
            disabled: child.disabled,
          ),
        );
      } else if (child is EOptionGroup<T>) {
        _collectOptions(child.children);
      }
    }
  }

  /// 过滤选项
  void _filterOptions(String keyword) {
    if (keyword.isEmpty) {
      setState(() {
        _filteredOptions = List.from(widget.children);
      });
      return;
    }

    // 这里简化实现，实际项目中可能需要更复杂的过滤逻辑
    setState(() {
      _filteredOptions = widget.children.where((child) {
        if (widget.filterMethod != null) {
          return widget.filterMethod!(keyword, child);
        }

        // 默认过滤逻辑
        if (child is EOption<T>) {
          return child.label.toLowerCase().contains(keyword.toLowerCase());
        } else if (child is EOptionGroup<T>) {
          // 检查分组内是否有匹配的选项
          return child.children.any((option) {
            if (option is EOption<T>) {
              return option.label.toLowerCase().contains(keyword.toLowerCase());
            }
            return false;
          });
        }
        return false;
      }).toList();
    });
  }

  /// 切换下拉菜单显示状态
  void _toggleDropdown() {
    if (widget.disabled) return;
    setState(() {
      _showDropdown = !_showDropdown;
    });
    widget.onVisibleChange?.call(_showDropdown);
  }

  /// 处理选项选择
  void _handleSelect(T value) {
    if (widget.disabled) return;

    dynamic newValue;
    if (widget.multiple) {
      // 多选逻辑
      List<dynamic> currentValues = List.from(widget.value ?? []);
      if (currentValues.contains(value)) {
        currentValues.remove(value);
      } else {
        if (widget.multipleLimit > 0 && currentValues.length >= widget.multipleLimit) {
          return;
        }
        currentValues.add(value);
      }
      newValue = currentValues;
    } else {
      // 单选逻辑
      newValue = value;
      _toggleDropdown(); // 单选时选择后关闭下拉框
    }

    // 清除搜索关键词（除非设置了reserveKeyword）
    if (!widget.reserveKeyword) {
      _searchController.clear();
      _filteredOptions = List.from(widget.children);
    }

    widget.onChange?.call(newValue);
  }

  /// 处理清空
  void _handleClear() {
    if (widget.disabled) return;
    widget.onChange?.call(widget.multiple ? [] : null);
    widget.onClear?.call();
    _searchController.clear();
  }

  /// 处理移除标签
  void _handleRemoveTag(dynamic value) {
    if (widget.disabled) return;
    List<dynamic> currentValues = List.from(widget.value ?? []);
    currentValues.remove(value);
    widget.onChange?.call(currentValues);
    widget.onRemoveTag?.call(value);
  }

  /// 获取选中的标签文本
  String? _getSelectedLabel(dynamic value) {
    if (value == null) return null;
    for (var option in _optionsCache) {
      if (option.value == value) {
        return option.label;
      }
    }
    return value.toString();
  }

  /// 获取输入框高度
  double _getInputHeight() {
    switch (widget.size) {
      case EInputSize.small:
        return 32.0;
      case EInputSize.large:
        return 40.0;
      default:
        return 36.0;
    }
  }

  /// 获取字体大小
  double _getFontSize() {
    switch (widget.size) {
      case EInputSize.small:
        return 12.0;
      case EInputSize.large:
        return 16.0;
      default:
        return 14.0;
    }
  }

  /// 获取边框颜色
  Color _getBorderColor() {
    if (widget.disabled) {
      return theme.borderColor.withOpacity(0.5);
    }

    if (_isFocused) {
      return theme.primaryColor;
    }

    return theme.borderColor;
  }

  /// 构建选中标签
  Widget _buildSelectedTags() {
    if (!widget.multiple) {
      // 单选模式
      final label = _getSelectedLabel(widget.value);
      return Text(
        label ?? '',
        style: TextStyle(
          color: theme.textPrimaryColor,
          fontSize: _getFontSize(),
        ),
        overflow: TextOverflow.ellipsis,
      );
    } else {
      // 多选模式
      if (widget.value == null || (widget.value as List).isEmpty) {
        return const SizedBox.shrink();
      }

      List<dynamic> values = List.from(widget.value);
      
      if (widget.collapseTags && values.length > 1) {
        // 折叠标签模式
        return Text(
          '已选择 ${values.length} 项',
          style: TextStyle(
            color: theme.textPrimaryColor,
            fontSize: _getFontSize(),
          ),
        );
      }

      // 显示所有标签
      return Wrap(
        spacing: 4,
        runSpacing: 4,
        children: values.map((value) {
          final label = _getSelectedLabel(value);
          return Chip(
            label: Text(
              label ?? '',
              style: TextStyle(
                fontSize: _getFontSize() - 2,
                color: theme.textPrimaryColor,
              ),
            ),
            backgroundColor: theme.primaryLight.withOpacity(0.2),
            deleteIcon: Icon(
              Icons.close, 
              size: 14,
              color: theme.textSecondaryColor,
            ),
            onDeleted: () => _handleRemoveTag(value),
            labelPadding: const EdgeInsets.symmetric(horizontal: 4),
            padding: const EdgeInsets.symmetric(horizontal: 4),
          );
        }).toList(),
      );
    }
  }

  /// 构建输入框或显示区域
  Widget _buildInputArea() {
    final height = _getInputHeight();
    final fontSize = _getFontSize();
    final borderColor = _getBorderColor();

    return Container(
      height: height,
      decoration: BoxDecoration(
        border: Border.all(color: borderColor, width: 1),
        borderRadius: BorderRadius.circular(4),
        color: Colors.white,
      ),
      child: GestureDetector(
        onTap: () {
          if (!widget.disabled) {
            _focusNode.requestFocus();
            if (widget.filterable) {
              // 如果是可搜索的，不自动打开下拉框，等待用户输入
            } else {
              _toggleDropdown();
            }
          }
        },
        child: Row(
          children: [
            if (widget.prefix != null) ...[
              widget.prefix!,
              const SizedBox(width: 8),
            ],
            Expanded(
              child: widget.filterable && widget.value == null || (widget.value is List && (widget.value as List).isEmpty) || !widget.multiple
                  ? TextField(
                      controller: _searchController,
                      focusNode: _focusNode,
                      decoration: InputDecoration(
                        border: InputBorder.none,
                        contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                        hintText: widget.placeholder,
                        hintStyle: TextStyle(
                          fontSize: fontSize,
                          color: theme.textPlaceholderColor,
                        ),
                        isDense: true,
                      ),
                      style: TextStyle(
                        fontSize: fontSize,
                        color: theme.textPrimaryColor,
                      ),
                      enabled: !widget.disabled,
                      onSubmitted: (value) {
                        if (widget.defaultFirstOption && _filteredOptions.isNotEmpty) {
                          // 选择第一个匹配的选项
                          // 这里简化实现，实际项目中可能需要更复杂的逻辑
                        }
                      },
                    )
                  : Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                      child: _buildSelectedTags(),
                    ),
            ),
            if (widget.clearable && widget.value != null && (!widget.multiple || (widget.value is List && (widget.value as List).isNotEmpty))) ...[
              IconButton(
                icon: Icon(
                  Icons.clear,
                  size: 16,
                  color: theme.textSecondaryColor,
                ),
                onPressed: _handleClear,
                padding: EdgeInsets.zero,
                constraints: const BoxConstraints(),
              ),
            ],
            IconButton(
              icon: Icon(
                _showDropdown ? Icons.arrow_drop_up : Icons.arrow_drop_down,
                size: 16,
                color: theme.textSecondaryColor,
              ),
              onPressed: _toggleDropdown,
              padding: EdgeInsets.zero,
              constraints: const BoxConstraints(),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建下拉菜单
  Widget _buildDropdown() {
    if (!_showDropdown) {
      return const SizedBox.shrink();
    }

    return Positioned(
      top: _getInputHeight() + 4,
      left: 0,
      right: 0,
      child: Material(
        elevation: 4,
        borderRadius: BorderRadius.circular(4),
        child: Container(
          constraints: BoxConstraints(
            maxHeight: 300,
          ),
          child: _buildDropdownContent(),
        ),
      ),
    );
  }

  /// 构建下拉菜单内容
  Widget _buildDropdownContent() {
    if (widget.loading) {
      return Container(
        padding: const EdgeInsets.all(16),
        alignment: Alignment.center,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircularProgressIndicator(
              strokeWidth: 2,
              color: theme.primaryColor,
              backgroundColor: theme.borderColor,
            ),
            const SizedBox(width: 8),
            Text(
              widget.loadingText,
              style: TextStyle(
                color: theme.textRegularColor,
                fontSize: 14,
              ),
            ),
          ],
        ),
      );
    }

    if (_filteredOptions.isEmpty) {
      if (widget.filterable && _searchController.text.isNotEmpty) {
        return Container(
          padding: const EdgeInsets.all(16),
          alignment: Alignment.center,
          child: Text(
            widget.noMatchText,
            style: TextStyle(
              color: theme.textSecondaryColor,
              fontSize: 14,
            ),
          ),
        );
      }

      if (widget.empty != null) {
        return widget.empty!;
      }

      return Container(
        padding: const EdgeInsets.all(16),
        alignment: Alignment.center,
        child: Text(
          widget.noDataText,
          style: TextStyle(
            color: theme.textSecondaryColor,
            fontSize: 14,
          ),
        ),
      );
    }

    // 渲染过滤后的选项
    return SingleChildScrollView(
      child: Column(
        children: _renderFilteredOptions(_filteredOptions),
      ),
    );
  }

  /// 渲染过滤后的选项
  List<Widget> _renderFilteredOptions(List<Widget> options) {
    return options.map((child) {
      if (child is EOption<T>) {
        bool isSelected = false;
        if (widget.multiple) {
          isSelected = widget.value != null && (widget.value as List).contains(child.value);
        } else {
          isSelected = widget.value == child.value;
        }

        return EOption<T>(
          value: child.value,
          label: child.label,
          disabled: widget.disabled || child.disabled,
          isSelected: isSelected,
          onSelect: _handleSelect,
        );
      } else if (child is EOptionGroup<T>) {
        // 处理分组选项
        return EOptionGroup<T>(
          label: child.label,
          disabled: widget.disabled || child.disabled,
          children: child.children.map((option) {
            if (option is EOption<T>) {
              bool isSelected = false;
              if (widget.multiple) {
                isSelected = widget.value != null && (widget.value as List).contains(option.value);
              } else {
                isSelected = widget.value == option.value;
              }

              return EOption<T>(
                value: option.value,
                label: option.label,
                disabled: widget.disabled || child.disabled || option.disabled,
                isSelected: isSelected,
                onSelect: _handleSelect,
              );
            }
            return option;
          }).toList(),
        );
      }
      return child;
    }).toList();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      child: Stack(
        children: [
          _buildInputArea(),
          _buildDropdown(),
        ],
      ),
    );
  }
}

/// 选项数据内部类
class _OptionData<T> {
  _OptionData({
    required this.value,
    required this.label,
    this.disabled = false,
  });

  final T value;
  final String label;
  final bool disabled;
}